# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
File    : serial_port.py
Time    : 2023/11/22 9:42
author  : mojin
Email   : 397135766@qq.com
-------------------------------------------------------------------------------
"""
import serial,time,json

import serial.tools.list_ports
from common.logger import Logger

class SerialPort():




    def get_port_list(self):

        # 获取可用串口列表
        available_ports = serial.tools.list_ports.comports()

        list_ports=[]
        list_ports_name = []
        # 输出每个可用串口的信息
        for port in available_ports:

            dic={
                'ports_name':port.device,
                'description': port.description,
                'hwid': port.hwid,
            }

            list_ports.append(dic)
            list_ports_name.append(port.device)

        ports_dic={
            "list_ports":list_ports,
            "list_ports_name":list_ports_name
        }
        Logger.info(ports_dic)

        return ports_dic


from PyQt5.QtCore import QThread, pyqtSignal


class SerialStart(QThread):

    serial_connect_status = pyqtSignal(int)  # 用于更新进度条的信号
    serial_data = pyqtSignal(str)  # 用于更新进度条的信号
    def __init__(self,prot_name,BAUD):
        super().__init__()
        self.prot_name=prot_name
        self.BAUD=BAUD
        self.serial_port_status=False


    def run(self):
        # 选择串口
        ser = serial.Serial(self.prot_name, int(self.BAUD), timeout=1)  # 将 'COM1' 替换为您要连接的实际串口名称 115200
        self.serial_port_status=True
        Logger.info('端口开启成功……')
        self.serial_connect_status.emit(0)  # 发送完成信号
        while True:
            # 读取串口数据
            if self.serial_port_status:
                #if ser.in_waiting > 0:
                    data = ser.readline()  # 按行读取数据
                    str = data.decode('utf-8')  # 将字节数据转换为字符串
                    str = str.replace("\r\n", "")
                    try:
                        data_list = str.split(",")
                        if '$GPYBM' not in data_list:
                            Logger.warning(f'串口消息：{str}')

                        else:
                            #data = '$GPYBM,SN10073809,033620.50,+37.374108529,+114.785541198,16.541,145.339,-1.425,-2.886,1.891,-0.034,3.450,4150812.439,37967.290,-1537.115,2887.487,4,4,35,2,0539,1.138,35,*65'

                            data_dic = {
                                "serialNumber": data_list[1],
                                "latitude": data_list[3],
                                "longitude": data_list[4],
                                "track": data_list[6],
                                "timestamp": f'{int(time.time() * 1000)}',
                                "groundSpeed": data_list[11],
                                "getGroundSpeed": data_list[11],
                            }
                            self.serial_data.emit(json.dumps(data_dic))
                    except Exception as e:

                        data_dic= {
                                    'serial_data':str,
                                    'error':e
                                    }

                        Logger.error(f'{data_dic}')
                    time.sleep(1)

            else:

                ser.close()
                Logger.info('端口关闭成功……')
                self.serial_connect_status.emit(1)  # 发送完成信号
                break



if __name__ == "__main__":
    SerialPort().get_port_list()